package com.fivefu.core.hik.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fivefu.base.common.utils.str.StrUtils;
import com.fivefu.core.hik.dto.response.CameraDetail;
import com.fivefu.core.hik.dto.response.CameraLonLatResp;
import com.fivefu.core.hik.entity.DbHikCamera;
import com.fivefu.core.hik.mapper.DbHikCameraMapper;
import com.fivefu.core.hik.services.DbHikCameraService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fivefu.module.dictionary.entity.DbSysDict;
import com.fivefu.module.dictionary.service.DbSysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 海康监控点表 服务实现类
 * </p>
 *
 * @author 
 * @since 2022-07-05 09:15:14
 */
@Service
public class DbHikCameraServiceImpl extends ServiceImpl<DbHikCameraMapper, DbHikCamera> implements DbHikCameraService {

    @Autowired
    private DbSysDictService dbSysDictService;

    /**
     * 通过唯一标识查询监控点信息
     * @param code
     * @return
     */
    public DbHikCamera queryHikCameraByCode(String code){
        QueryWrapper<DbHikCamera> wrapper = new QueryWrapper<>();
        wrapper.eq("camera_index_code", code);
//        wrapper.eq("is_delete",0);
        DbHikCamera camera = baseMapper.selectOne(wrapper);
        return camera;
    }

    /**
     * 编辑海康监控点信息
     * @param camera 监控点信息
     */
    @Override
    public void editHikCamera(DbHikCamera camera){
        String code = camera.getCameraIndexCode();
        //通过唯一标识查询监控点信息
        DbHikCamera oldCamera = queryHikCameraByCode(code);
        if (oldCamera != null){
            camera.setId(oldCamera.getId());
        }

        LocalDateTime time = LocalDateTime.now();
        camera.setUpdatedTime(time);
        //判断监控点是否删除
        if (camera.getCameraStatus() != null){
            if (camera.getCameraStatus() < 0){
                camera.setIsDelete(1);
            }else{
                camera.setIsDelete(0);
            }
        } else {
            camera.setCameraStatus(0);
            camera.setIsDelete(0);
        }
        //判断监控点类型是否为空
        if (StrUtils.isNotNull(camera.getCameraType())) {
            DbSysDict dict = dbSysDictService.queryDictByValue("CTP", camera.getCameraType());
            if(dict != null){
                camera.setCameraType(dict.getDictCode());
            }
        }
        //判断接入协议是否为空
        if (StrUtils.isNotNull(camera.getTreatyType())) {
            DbSysDict dict = dbSysDictService.queryDictByValue("TTP", camera.getTreatyType());
            if(dict != null){
                camera.setTreatyType(dict.getDictCode());
            }
        }
        //判断智能后分析能力集是否为空
        if (StrUtils.isNotNull(camera.getIntelligentSet())) {
            DbSysDict dict = dbSysDictService.queryDictByValue("IG", camera.getIntelligentSet());
            if(dict != null){
                camera.setIntelligentSet(dict.getDictCode());
            }
        }
        //判断安装位置是否为空
        if (StrUtils.isNotNull(camera.getInstallLocation())) {
            DbSysDict dict = dbSysDictService.queryDictByValue("IL", camera.getInstallLocation());
            if(dict != null){
                camera.setInstallLocation(dict.getDictCode());
            }
        }
        //判断传输协议是否为空
        if (StrUtils.isNotNull(camera.getTransType())) {
            DbSysDict dict = dbSysDictService.queryDictByValue("TT", camera.getTransType());
            if(dict != null){
                camera.setTransType(dict.getDictCode());
            }
        }
        //判断视频通道类型是否为空
        if (StrUtils.isNotNull(camera.getChannelType())) {
            DbSysDict dict = dbSysDictService.queryDictByValue("CH", camera.getChannelType());
            if(dict != null){
                camera.setChannelType(dict.getDictCode());
            }
        }
        //判断录像存储位置是否为空
        if (StrUtils.isNotNull(camera.getRecordLocation())) {
            String recordLocation = camera.getRecordLocation();
            //多录像存储用”_“分割
            String dictCode = queryDictCodes("RL",recordLocation,"_");
            camera.setRecordLocation(dictCode);
        }
        //判断设备能力集是否为空
        if (StrUtils.isNotNull(camera.getCapability())) {
            String capability = camera.getCapability();
            String suffix = ",";
            if (capability.startsWith("@") && capability.endsWith("@")){
                capability = capability.substring(1,capability.length() - 1);
                suffix = "@";
            }
            //多设备能力用”,“分割

            String dictCode = queryDictCodes("CP",capability,suffix);
            camera.setCapability(dictCode);
        }
        if (camera.getId() != null){
            baseMapper.updateById(camera);
        }else{
            camera.setCreatedTime(time);
            if (camera.getIsDelete() == null){
                camera.setIsDelete(0);
            }
            baseMapper.insert(camera);
        }
    }

    /**
     * 获得监控点经纬度
     * @param cameraName 监控点名称
     * @return
     */
    @Override
    public List<CameraLonLatResp> queryCameraLonLat(String cameraName) {
        QueryWrapper<DbHikCamera> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        wrapper= StrUtils.isNull(cameraName) ? wrapper :wrapper.like("camera_name",cameraName);
        List<DbHikCamera> list = this.list(wrapper);
        List<CameraLonLatResp> lonLatResps = new ArrayList<>();
        for (DbHikCamera dbHikCamera : list) {
            CameraLonLatResp resp = new CameraLonLatResp();
            resp.setId(dbHikCamera.getId());
            resp.setCameraName(dbHikCamera.getCameraName());//监控点名称
            resp.setLongitude(dbHikCamera.getLongitude());//经度
            resp.setLatitude(dbHikCamera.getLatitude());//纬度
            resp.setCameraIndexCode(dbHikCamera.getCameraIndexCode());//监控点唯一标识
            lonLatResps.add(resp);
        }
        return lonLatResps;
    }

    /**
     * 获得监控点详情
     * @param id 监控点编号
     * @return
     */
    @Override
    public CameraDetail queryCameraDetail(Integer id) {
        //根据监控点编号查询监控点详情
        DbHikCamera dbHikCamera = baseMapper.selectById(id);
        //组装参数
        CameraDetail detail = new CameraDetail();
        detail.setId(dbHikCamera.getId());
        detail.setCreatedTime(dbHikCamera.getCreatedTime());
        detail.setCreatedBy(dbHikCamera.getCreatedBy());
        detail.setIsDelete(dbHikCamera.getIsDelete());
        if (dbHikCamera.getIsDelete()!=null){
            if (dbHikCamera.getIsDelete()==1){
                detail.setCnDelete("是");
            }else {
                detail.setCnDelete("否");
            }
        }
        detail.setUpdatedBy(dbHikCamera.getUpdatedBy());
        detail.setUpdatedTime(dbHikCamera.getUpdatedTime());
        detail.setRemark(dbHikCamera.getRemark());//备注
        detail.setCameraIndexCode(dbHikCamera.getCameraIndexCode());//监控点唯一标识
        detail.setCameraName(dbHikCamera.getCameraName());//监控点名称
        detail.setCameraType(dbHikCamera.getCameraType());//监控点类型
        if (StrUtils.isNotNull(dbHikCamera.getCameraType())){
            detail.setCameraTypeName(queryDictNameByCode(dbHikCamera.getCameraType()));
        }
        detail.setElevation(dbHikCamera.getElevation());//海拔
        detail.setLongitude(dbHikCamera.getLongitude());//经度
        detail.setLatitude(dbHikCamera.getLatitude());//纬度
        detail.setCapability(dbHikCamera.getCapability());//能量集
        if (StrUtils.isNotNull(dbHikCamera.getCapability())){
            /*String result = "";
            String[] split = dbHikCamera.getCapability().split(",");
            for (String s : split) {
                result += dbSysDictService.queryNameByCode(s)+",";
            }
            String substring = result.substring(0, result.length() - 1);*/
            String substring = queryDictNameByCode(dbHikCamera.getCapability(),",");
            detail.setCapabilityName(substring);
        }
        detail.setChannelNo(dbHikCamera.getChannelNo());//通道编号
        detail.setChannelType(dbHikCamera.getChannelType());//通道类型
        if (StrUtils.isNotNull(dbHikCamera.getChannelType())){
            detail.setChannelTypeName(queryDictNameByCode(dbHikCamera.getChannelType()));
        }
        detail.setRecordLocation(dbHikCamera.getRecordLocation());//录像存储位置
        if (StrUtils.isNotNull(dbHikCamera.getRecordLocation())){
            String substring = queryDictNameByCode(dbHikCamera.getRecordLocation(),",");
            detail.setRecordLocationName(substring);
        }
        detail.setIntelligentSet(dbHikCamera.getIntelligentSet());//智能分析能量集
        if (StrUtils.isNotNull(dbHikCamera.getIntelligentSet())){
            String substring = queryDictNameByCode(dbHikCamera.getIntelligentSet(),",");
            detail.setIntelligentSetName(substring);
        }
        detail.setEncodeDevIndexCode(dbHikCamera.getEncodeDevIndexCode());//所属编码设备唯一标识
        detail.setEncodeDevResourceType(dbHikCamera.getEncodeDevResourceType());//所属设备类型
        if (StrUtils.isNotNull(dbHikCamera.getEncodeDevResourceType())){
            detail.setEncodeDevResourceTypeName(queryDictNameByCode(dbHikCamera.getEncodeDevResourceType()));
        }
        detail.setGbIndexCode(dbHikCamera.getGbIndexCode());//国标编号
        detail.setInstallLocation(dbHikCamera.getInstallLocation());//安装位置
        if (StrUtils.isNotNull(dbHikCamera.getInstallLocation())){
            detail.setInstallLocationName(queryDictNameByCode(dbHikCamera.getInstallLocation()));
        }
        detail.setKeyBoardCode(dbHikCamera.getKeyBoardCode());//键盘控制码
        detail.setPixel(dbHikCamera.getPixel());//摄像机像素
        detail.setPtz(dbHikCamera.getPtz());//云镜类型
        if (StrUtils.isNotNull(dbHikCamera.getPtz())){
            detail.setPtzName(queryDictNameByCode(dbHikCamera.getPtz()));
        }
        detail.setPtzController(dbHikCamera.getPtzController());//云台控制
        if (StrUtils.isNotNull(dbHikCamera.getPtzController())){
            detail.setPtzControllerName(queryDictNameByCode(dbHikCamera.getPtzController()));
        }
        detail.setRegionIndexCode(dbHikCamera.getRegionIndexCode());//所属区域唯一标识
        detail.setOnlineStatus(dbHikCamera.getOnlineStatus());//在线状态（0-未知，1-在线，2-离线）
        if (dbHikCamera.getOnlineStatus()!=null){
                detail.setOnlineStatusName(queryDictNameByCode(String.valueOf(dbHikCamera.getOnlineStatus())));
        }
        detail.setTransType(dbHikCamera.getTransType());//传输协议
        if (StrUtils.isNotNull(dbHikCamera.getTransType())){
            detail.setTransTypeName(queryDictNameByCode(dbHikCamera.getTransType()));
        }
        detail.setTreatyType(dbHikCamera.getTreatyType());//接入协议
        if (StrUtils.isNotNull(dbHikCamera.getTreatyType())){
            detail.setTreatyTypeName(queryDictNameByCode(dbHikCamera.getTreatyType()));
        }
        detail.setViewshed(dbHikCamera.getViewshed());//可视域相关
        detail.setCreateTime(dbHikCamera.getCreateTime());//创建时间
        detail.setUpdateTime(dbHikCamera.getUpdateTime());//更新时间
        detail.setCameraStatus(dbHikCamera.getCameraStatus());//状态小于0则代表资源已被删除
        if (dbHikCamera.getCameraStatus()!=null){
            if (dbHikCamera.getCameraStatus()<0){
                detail.setCnCameraStatus("资源已被删除");
            }else {
                detail.setCnCameraStatus("资源未被删除");
            }
        }
        detail.setDisOrder(dbHikCamera.getDisOrder());//数据在界面上显示的顺序
        return detail;
    }

    @Override
    public List<String> queryCameraIds() {
        QueryWrapper<DbHikCamera> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        //wrapper.eq("camera_status",0);
        wrapper.select("camera_index_code");
        List<DbHikCamera> list = baseMapper.selectList(wrapper);
        List<String> cameraIDs = list.stream().map(k -> k.getCameraIndexCode()).collect(Collectors.toList());
        return cameraIDs;
    }

    /**
     * 通过唯一标识查询探头信息
     * @param cameraIndexCode 探头唯一标识
     * @return
     */
    @Override
   public DbHikCamera queryCameraByIndexCode(String cameraIndexCode){
       QueryWrapper<DbHikCamera> wrapper = new QueryWrapper<>();
       wrapper.eq("is_delete",0);
       wrapper.eq("camera_index_code", cameraIndexCode);
       DbHikCamera detail = baseMapper.selectOne(wrapper);
       return detail;
   }

    /**
     * 获取数据字典编号
     * @param dictParentCode
     * @param dictValue
     * @param suffix
     * @return
     */
    @Override
   public String queryDictCodes(String dictParentCode, String dictValue, String suffix){
       String[] dictValueArr = dictValue.split(suffix);
       List<DbSysDict> dictList = dbSysDictService.queryDictCodesByValue(dictParentCode, dictValueArr);
       List<String> list = dictList.stream().map(k -> k.getDictCode()).collect(Collectors.toList());
       return String.join(",", list);
   }

    /**
     * 获取数据字典名称
     * @param dictCode
     * @return
     */
   public String queryDictNameByCode(String dictCode){
       DbSysDict dict = dbSysDictService.queryDictDetail(null, dictCode);
       if (dict != null){
           return dict.getDictName();
       }
       return null;
   }

    /**
     * 获取数据字典名称集合
     * @param dictCode
     * @return
     */
    public String queryDictNameByCode(String dictCode,String suffix){
        List<String> dictNames = new ArrayList<>();
        String[] dictCodeArr = dictCode.split(suffix);
        for (String code : dictCodeArr) {
            String dictName = queryDictNameByCode(code);
            dictNames.add(dictName);
        }
        return String.join(",",dictNames);
    }

    /**
     * 查询海康所有监控点信息
     * @return
     */
    @Override
    public List<DbHikCamera> queryAllCamera() {
        QueryWrapper<DbHikCamera> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        wrapper.eq("camera_status",0);
        List<DbHikCamera> resultList = baseMapper.selectList(wrapper);
        return resultList;
    }

    /**
     * 修改监控点在线状态
     * @param cameraIndexCode 监控点唯一编号
     * @param onlineStatus 在线状态（0-未知，1-在线，2-离线）
     */
    @Override
    public void changeCameraOnlineStatus(String cameraIndexCode, Integer onlineStatus){
        UpdateWrapper<DbHikCamera> wrapper = new UpdateWrapper<>();
        wrapper.eq("is_delete",0);
        wrapper.eq("camera_index_code", cameraIndexCode);

        wrapper.set("online_status",onlineStatus);

        baseMapper.update(null, wrapper);
    }


    /**
     * 删除多余的监控点数据
     * @param cameraIndexCodes
     * @param userId
     */
    @Override
    public void deleteHikCamera(List<String> cameraIndexCodes, String userId) {
        QueryWrapper<DbHikCamera> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0);
        if (!cameraIndexCodes.isEmpty()) {
            wrapper.notIn("camera_index_code",cameraIndexCodes);
        }

        DbHikCamera hikCamera = new DbHikCamera();
        hikCamera.setUpdatedBy(userId);
        hikCamera.setUpdatedTime(LocalDateTime.now());
        hikCamera.setIsDelete(1);
        baseMapper.update(hikCamera,wrapper);
    }
}
